import { getAppToken } from "../api/system"
import { JudgmentExpiration } from "./judgmentExpiration"

class APPToken {
  JudgmentExpirationInstance = new JudgmentExpiration()
  isExpire = false
  constructor() {
   
  }
  //定时任务，token 过期前重新获取token
  timerTask() {
    const appExpire = wx.getStorageSync('appExpire') || 0
    const appTokenLoginTime = wx.getStorageSync('appTokenLoginTime') || 0
    this.JudgmentExpirationInstance.init(appExpire, appTokenLoginTime, () => {
      //倒计时结束 重新获取token
      this.getToken()
    })
  }
  getToken() {
    return new Promise((resolve) => {
      getAppToken().then((res: any) => {
        wx.setStorageSync('appTokenStatus', true)
        wx.setStorageSync('appToken', res.result.accessToken)
        wx.setStorageSync('appExpire', res.result.expire)
        wx.setStorageSync('appTokenLoginTime', Math.floor(Date.now() / 1000))

        this.timerTask()
        resolve(res.result.accessToken)
      })
    });
  }
  removeStorage(){
    wx.removeStorageSync('appTokenStatus')
    wx.removeStorageSync('appToken')
    wx.removeStorageSync('appExpire')
    wx.removeStorageSync('appTokenLoginTime')
  }
  init() {
    //用户进入小程序，根据过期时间判断登录是否过期
     //获取本地存储的过期时间及登录时间
     const appExpire = wx.getStorageSync('appExpire') || 0
     const appTokenLoginTime = wx.getStorageSync('appTokenLoginTime') || 0
     this.isExpire = this.JudgmentExpirationInstance.expire(appExpire, appTokenLoginTime)
    if (this.isExpire) {
      console.log('信息expire')
      //重新获取
      this.getToken()
    } else {
      console.log('信息未过期')
      //没有过期，开启定时器
      this.timerTask()
    }
  }
}
export const appTokenInstance = new APPToken()
